﻿using IdentityModel.AspNetCore.OAuth2Introspection;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Text.Encodings.Web;

namespace FileStorageCenter.EFCore.Authentication;

public class DefaultAuthenticationOptions : AuthenticationSchemeOptions
{
    public Func<HttpRequest, string> TokenRetriever { get; set; } = TokenRetrieval.FromAuthorizationHeader();

}

public class DefaultAuthenticationHandlerPlatform : AuthenticationHandler<DefaultAuthenticationOptions>
{
    public DefaultAuthenticationHandlerPlatform(
        IOptionsMonitor<DefaultAuthenticationOptions> options,
        ILoggerFactory logger,
        UrlEncoder encoder,
        ISystemClock clock)
        : base(options, logger, encoder, clock)
    {

    }

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        return AuthenticateResult.Success(new AuthenticationTicket(new System.Security.Claims.ClaimsPrincipal(), "External:IdSrv"));
        var token = Options.TokenRetriever(Context.Request);

        try
        {
            AuthenticateResult authResult;
            if (token != null)
            {
                authResult = await Context.AuthenticateAsync("External:IdSrv");

                return !authResult.Succeeded
                    ? AuthenticateResult.Fail("Unauthorized")
                    : AuthenticateResult.Success(new AuthenticationTicket(authResult.Principal, "External:IdSrv"));
            }

            return AuthenticateResult.Fail("Unauthorized");
        }
        catch (Exception ex)
        {
            return AuthenticateResult.Fail(ex);
        }
    }
}
